<?php
namespace app\admin\controller;
use app\admin\model\GroupRole;
use app\admin\model\Group;
use app\admin\controller\AdminAuth;
use app\admin\model\Role;
use think\Db;
use think\Validate;
use think\Image;
use think\Request;
class GroupController extends AdminAuth
{
	//模块基本信息
	private $data = array(
		'module_name' => '部门',
		'module_url'  => '/admin/Group/',
		'module_slug' => 'Users',
		'upload_path' => UPLOAD_PATH,
		'upload_url'  => '/public/uploads/',
		);


    /**
     * [index 获取部门数据列表]
     * @return [type] [description]
     */
    public function index()
    {
        //获取前端参数
        $list =  Group::where('status','>=','0')->order('id', 'ASC')->paginate();
        $this->assign('data',$this->data);
        $this->assign('list',$list);
        return $this->fetch();
    }

    /**
     * [create 创建部门数据页面]
     * @return [type] [description]
     */
    public function create()
    {
        $groups = Group::where('status',1)->column('group_name','id');
        $level = [0 => '顶级部门', 1 => '一级部门', 2 => '二级部门', 3 => '三级部门', 4 => '四级部门'];

    	$this->data['edit_fields'] = array(
			'group_name' => array('type' => 'text', 'label'     => '部门名称'),
            'pid'        => array('type' => 'select', 'label' => '上级部门','default' => $groups),
			'level'      => array('type' => 'select', 'label' => '部门等级','default' => $level),
			'status'     => array('type' => 'radio', 'label' => '状态','default'=> array(-1 => '删除', 0 => '禁用', 1 => '正常', 2 => '待审核')),
        );

        //默认值设置
        $item['status'] = '正常';

        $this->assign('item',$item);
        $this->assign('data',$this->data);
        return view();
    }

    /**
     * [add 新增部门数据ACTION，create()页面表单数据提交到这里]
     * @return [type] [description]
     */
    public function add()
    {
        $Group = new Group;
        $data = input('post.');

        $rule = [
            'group_name|部门名称' => 'require|alphaDash|min:2|unique:Group,group_name',
        ];
        // 数据验证
        $validate = new Validate($rule);
        $result   = $validate->check($data);
        if(!$result){
            return  $this->error($validate->getError());
        }

        $data['create_time'] = time();
        $data['update_time'] = time();


        if ($id = $Group->validate(true)->insertGetId($data)) {
            return $this->success('部门添加成功',$this->data['module_url'].$id);
        } else {
            return $this->error($Group->getError());
        }
    }



    /**
     * [read 读取部门数据]
     * @param  string $id [用户ID]
     * @return [type]     [description]
     */
    public function read($id='')
    {
        $groups = Group::where('status',1)->column('group_name','id');
        $level = [0 => '顶级部门', 1 => '一级部门', 2 => '二级部门', 3 => '三级部门', 4 => '四级部门'];
        $this->data['edit_fields'] = array(
			'group_name' => array('type' => 'text', 'label'     => '部门名称'),
            'pid'        => array('type' => 'select', 'label' => '上级部门','default' => $groups),
            'level'      => array('type' => 'select', 'label' => '部门等级','default' => $level),
			'status'   => array('type' => 'radio', 'label' => '状态','default'=> array(-1 => '删除', 0 => '禁用', 1 => '正常')),
        );

        //默认值设置
        $item = Group::get($id);
        $this->assign('item',$item);
        $this->assign('data',$this->data);
        return view();
    }

    /**
     * [update 更新部门数据，read()提交表单数据到这里]
     * @param  [type] $id [description]
     * @return [type]     [description]
     */
    public function update($id)
    {
        $Group = new Group;
        $data = input('post.');

        $preview = $Group->where(array('group_name'=>$data['group_name']))->find();


        $rule = [
            'group_name|部门名称' => 'require|min:2',
        ];
        $msg = [];


        // 数据验证
        $validate = new Validate($rule,$msg);
        $result   = $validate->check($data);
        if(!$result){
            return  $this->error($validate->getError());
        }
        $data['id'] = $id;

        if ($Group->update($data)) {
            return $this->success('部门信息更新成功',$this->data['module_url'].$id);
        } else {
            return  $this->error($Group->getError());
        }
    }

    /**
     * [delete 删除部门数据(伪删除)]
     * @param  [type] $id [表ID]
     * @return [type]     [description]
     */
    public function delete($id)
    {
        $Group = new Group;
        $data['id'] = $id;
        $data['status'] = -1;
        if ($Group->update($data)) {
        	$data['error'] = 0;
        	$data['msg'] = '删除成功';
        } else {
        	$data['error'] = 1;
        	$data['msg'] = '删除失败';
        }
        return $data;

        // 真.删除，不想用伪删除，请用这段
        // $Group = Group::get($id);
        // if ($Group) {
        //     $Group->delete();
        //     $data['error'] = 0;
        // 	$data['msg'] = '删除成功';
        // } else {
        // 	$data['error'] = 1;
        // 	$data['msg'] = '删除失败';
        // }
        // return $data;
    }

    /**
     * [role_list 读取该部门所拥有的角色列表]
     * @param $id
     */
    public function role_list($id){

        //查询该部门拥有的角色
        $list = GroupRole::where('group_id',$id)->column('role_id');

        //查询所有角色
        $all_roles = Role::where('status','>',0)->column('name','id');

        //查询该部门信息
        $group_info = Group::where('id',$id)->column('*');
//dump($group_info);exit;
        //默认值设置
        $item['id'] = $id;


        $this->assign('item',$item);
        $this->assign('list',$list);
        $this->assign('group_info',$group_info);
        $this->assign('all_roles',$all_roles);
        $this->assign('data',$this->data);
        return $this->fetch('group/role_list');
    }

    /**
     * [add 新增部门角色数据ACTION，create()页面表单数据提交到这里]
     * @return [type] [description]
     */
    public function role_add()
    {
        $GroupRole = new GroupRole();
        $data = input('post.');

        $rule = [
            'group_id|部门ID' => 'require',
        ];
        // 数据验证
        $validate = new Validate($rule);

        $result   = $validate->check($data);

        if(!$result){
            return  $this->error($validate->getError());
        }

        $data['create_time'] = time();
        $data['update_time'] = time();

        //查询表中原先是否有角色
        $origin_role = GroupRole::where('group_id',$data['group_id'])->find();

        if($origin_role){
            //删除原有的角色
            GroupRole::where('group_id',$data['group_id'])->delete();
        }

        if(count($data['role_id']) > 0) {
            $sql = 'insert into tp_group_role (`group_id`,`role_id`) values ';
            foreach($data['role_id'] as $v){
                $sql .= "(".$data['group_id']."," .$v."),";
            }
            $sql = rtrim($sql, ',');
            Db::query($sql);
        }

        return $this->success('操作成功',$this->data['module_url'].'role_list/'.$data['group_id']);
    }
}